package geneticsatsolver;

import java.util.Random;

/**
 * Class Individual represent an individual of the population
 * 
 * @author igor
 */
public class Individual {

    private boolean[] chromosome = null;
    public int len;
    public double fitness;

    /**
     * Generate random individual
     *
     * @param l length of individual chromosome
     */
    public Individual(int l) {
        this.len = l;
        this.chromosome = new boolean[len];
        Random r = new Random();
        for (int i = 0; i < this.len; i++) {
            chromosome[i] = r.nextBoolean();
        }
    }

    /**
     * Generate individual with specified chormosome
     *
     * @param ch chromosome to set
     */
    public Individual(boolean[] ch) {
        this.len = ch.length;
        this.chromosome = ch;
    }

    /**
     * Compute fitness of the individual
     *
     * @param problem   problem for fitness calculation
     * @return      fitness of individual
     */
    public double fitness(Problem problem) {
        this.fitness = problem.verify(chromosome);
        return fitness;
    }

    /**
     * Return the chromosome of the individual
     *
     * @return  chormosome
     */
    public boolean[] getChromosome() {
        return this.chromosome;
    }

    /**
     * Flip a random bit of chromosome
     */
    public void mutate() {
        int p = (int) (Math.random() * len);
        chromosome[p] = !chromosome[p];
    }
}
